import heapq
import json

from querier.esquerier import ElasticSearchQuerier
import utils.utils as utils
import math
import operator
import re

MINIMUM_SHOULD_MATCH = '5<85% 10<9'
MAX_BRANDS = 40
MAX_KEYWORDS = 10


class WechatBrandKOLMatchQuerier(ElasticSearchQuerier):
    def __init__(self, kol_match, brand_info):
        super(WechatBrandKOLMatchQuerier, self).__init__(None, None, None)
        self.kol_match = kol_match
        self.brand_info = brand_info

    def search(self, args):
        term = args.get('brand', '')
        filters = args.get('filters', {})
        filters = filters if filters else {}
        order = args.get('order_by', utils.ORDER_OVERALL)
        order = order if order else utils.ORDER_OVERALL
        from_ = args.get('from', 0)
        from_ = from_ if from_ else 0
        size_ = args.get('size', 10)
        size_ = size_ if size_ else 10
        highlight = args.get('highlight', False)
        highlight = highlight if highlight in (True, False) else False
        min_relative = args.get('min_relative', 0.0)
        min_relative = min_relative if min_relative else 0.0

        max_relative = args.get('max_relative', 20.0)
        max_relative = max_relative if max_relative else 20.0

        term = term if term else ''
        result = self.brand_info.search({"brand": term})
        keywords = result.get('keywords', [])
        keywords = ' '.join([k.get('text') for k in keywords][0:MAX_KEYWORDS])
        kol_match_args = {
            "term": keywords,
            "from": from_,
            "size": size_,
            'filters': filters,
            'highlight': highlight,
            'min_relative': min_relative,
            'max_relative': max_relative,
            'order_by': order,
        }
        return self.kol_match.search(kol_match_args)

    def _build_query(self, args): pass

    def _build_result(self, es_result, param): pass
